﻿// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Collections.Specialized;
using System.Linq;

namespace Microsoft.Internal.Collections
{
    internal class NotifyCollectionChangedHelper
    {
        private NotifyCollectionChangedEventHandler _collectionChanged;
        private readonly object _target;
        private readonly INotifyCollectionChanged _source;

        public NotifyCollectionChangedHelper(object target, INotifyCollectionChanged source)
        {
            this._target = target;
            this._source = source;
        }

        public event NotifyCollectionChangedEventHandler CollectionChanged
        {
            add
            {
                if (value != null)
                {
                    if (this._collectionChanged == null)
                    {
                        this._source.CollectionChanged += this.Callback;
                    }

                    this._collectionChanged = (NotifyCollectionChangedEventHandler)Delegate.Combine(this._collectionChanged, value);
                }
            }
            remove
            {
                if (value != null)
                {
                    this._collectionChanged = (NotifyCollectionChangedEventHandler)Delegate.Remove(this._collectionChanged, value);
                    if (this._collectionChanged == null)
                    {
                        this._source.CollectionChanged -= this.Callback;
                    }
                }
            }
        }

        private void Callback(object sender, NotifyCollectionChangedEventArgs args)
        {
            Assumes.NotNull(this._collectionChanged);

            // change sender to be the sequence
            this._collectionChanged(this._target, args);
        }
    }
}
